﻿using System.IO;
using System.Text;
using System.Xml.Linq;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.Linq;
using SP2010DevExtensions.Helper;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;

namespace SP2010DevExtensions.ItemTemplateWizard
{
    public class CustomActionWizard : IWizard
    {

        private WizardWindow wizardPage;

        #region IWizard Methods

        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary,
            WizardRunKind runKind, object[] customParams)
        {

            var dte = automationObject as DTE;
            Project project = null;
            if (dte != null)
            {
                var projects = dte.ActiveSolutionProjects as object[];
                if ((projects != null) && (projects.Length > 0))
                {
                    project = projects[0] as Project;
                }
            }


            #region SetTokenReplacement for SVC file type
            VsPackageHelper.AddSVcTokenExtensionReplacement(dte);
            //var dteType = (DTE)Package.GetGlobalService(typeof(DTE));

            //var globalOleServiceProvider = (IOleServiceProvider)dteType;
            //var globalServiceProvider = new ServiceProvider(globalOleServiceProvider);

            //var sln = globalServiceProvider.GetService(typeof(SVsSolution)) as IVsSolution;


            //IVsHierarchy hiearachy = null;

            //sln.GetProjectOfUniqueName(dte.Solution.Projects.Item(1).FullName, out hiearachy);

            //var buildPropStorage = (IVsBuildPropertyStorage)hiearachy;

            //ErrorHandler.ThrowOnFailure(buildPropStorage.SetPropertyValue("TokenReplacementFileExtensions", String.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE, "svc"));
            #endregion

            #region Create SharePoint Root's ISAPI folder
            //var shareProjectService = (ISharePointProjectService)globalServiceProvider.GetService(typeof(ISharePointProjectService));
            //var sharePointProject = shareProjectService.Convert<Project, ISharePointProject>(project);

            //if (sharePointProject != null)
            //{
            //    var layoutFolder = sharePointProject.MappedFolders.Where(mf => mf.FolderType == MappedFolderType.SharePointRoot).FirstOrDefault();
            //    if (layoutFolder == null)
            //    {
            //        var rootFolder = sharePointProject.MappedFolders.Add(MappedFolderType.SharePointRoot);
            //        var pi = shareProjectService.Convert<ISharePointProjectItem, ProjectItem>(rootFolder);
            //        pi.ProjectItems.AddFolder("ISAPI");
            //    }
            //}
            SharePointMappingFolderHelper.EnsureISAPIFolderExists(project);
            #endregion

            wizardPage = new WizardWindow();
            bool? dialogCompleted = wizardPage.ShowModal();

            if (dialogCompleted == true)
            {
                PopulateReplacementDictionary(replacementsDictionary);
            }
            else
            {
                throw new WizardCancelledException();
            }

        }




        // Always return true; this IWizard implementation throws a WizardCancelledException
        // that is handled by Visual Studio if the user cancels the wizard.
        public bool ShouldAddProjectItem(string filePath)
        {
            return true;
        }

        // The following IWizard methods are not implemented in this example.
        public void BeforeOpeningFile(ProjectItem projectItem)
        {

        }

        public void ProjectFinishedGenerating(Project project)
        {
            
        }

        public void ProjectItemFinishedGenerating(ProjectItem projectItem)
        {
            try
            {
                //http://msdn.microsoft.com/en-us/library/bb166197.aspx
                //http://msdn.microsoft.com/en-us/library/bb166517.aspx


                //var package = new VSPackageTemplatePackage();
                //var v = package.GetMyService(typeof (IVsUIShell));
                //var ivsSoltion = package.GetMyService(typeof (SVsSolution)) as IVsSolution;
                //var dte = package.GetMyService(typeof(SDTE)) as DTE;
                //IVsHierarchy hierachy = null;
                //if (ivsSoltion != null && dte != null) 
                //    ivsSoltion.GetProjectOfUniqueName(dte.Solution.Projects.Item(1).FullName, out hierachy);
                //var buildPropStroage = (IVsBuildPropertyStorage)hierachy;
                //if (buildPropStroage != null) ErrorHandler.ThrowOnFailure(buildPropStroage.SetPropertyValue("MyCustomProperty", string.Empty, (uint) _PersistStorageType.PST_PROJECT_FILE, "Value"));



               

               





                //Configuration config = projectItem.ContainingProject.ConfigurationManager.ActiveConfiguration;
                //config.Properties.Item("man").Value = "sohel";
                //projectItem.ContainingProject.Save();
                //projectItem.ContainingProject.Save();

               
                //var properties = projectItem.ContainingProject.Properties;
                //foreach (Property p in properties)
                //{
                //    if(p!=null&&p.Value!=null && p.Name!=null)
                //    Console.WriteLine("{0}=={1}",p.Name,p.Value);
                //}                
            }
            catch(Exception exp)
            {
                
            }


        }

        public void RunFinished()
        {
        }

        #endregion

        private void PopulateReplacementDictionary(Dictionary<string, string> replacementsDictionary)
        {
            replacementsDictionary.Add("$SharePointWCFServiceFactory$", wizardPage.ServiceFactoryType);

            replacementsDictionary.Add("$IdValue$", Guid.NewGuid().ToString());
            replacementsDictionary.Add("$MethodName$", wizardPage.cmbAspNetCompatibilityMode.Text);

            if (wizardPage.chkEnableMexEndPoint.IsChecked.HasValue && wizardPage.chkEnableMexEndPoint.IsChecked.Value)
            {
                replacementsDictionary.Add("$MetaExchange$", "[BasicHttpBindingServiceMetadataExchangeEndpointAttribute]");
            }
            else
            {
                replacementsDictionary.Add("$MetaExchange$",string.Empty);
            }

            replacementsDictionary.Add("$CompatibilityMode$", wizardPage.cmbAspNetCompatibilityMode.Text);

        }
    }
}

